from django.shortcuts import render
from rest_framework.response import Response
from home import models,homeser
from rest_framework.views import APIView
from django.core.cache import cache
# Create your views here.

class HeadNav(APIView):
    def get(self,request):
        # 首先设置该接口的缓存key
        key = "headnav"
        # 去缓存中读数据
        navlist = cache.get(key)
        if navlist:
            return Response({"code":200,"msg":"ok",'data':navlist})
        # 展示头部导航 有效的数据 按照order排序
        navlist = models.Nav.objects.filter(position=0,flag=True).order_by('order')
        ser = homeser.NavSerializer(navlist,many=True)
        # 将数据添加到缓存中
        cache.set(key,ser.data,60*60*24*7)
        return Response({"code":200,"msg":"ok",'data':ser.data})

class FootNav(APIView):
    def get(self,request):
        # 首先设置该接口的缓存key
        key = "footnav"
        # 去缓存中读数据
        navlist = cache.get(key)
        if navlist:
            return Response({"code":200,"msg":"ok",'data':navlist})
        # 展示底部导航 有效的数据 按照order排序
        navlist = models.Nav.objects.filter(position=1,flag=True).order_by('order')
        ser = homeser.NavSerializer(navlist,many=True)
        # 将数据添加到缓存中
        cache.set(key,ser.data,60*60*24*7)
        return Response({"code":200,"msg":"ok",'data':ser.data})


#banner
class Banner(APIView):
    def get(self,request):
        key = 'banner'
        banner = cache.get(key)
        if banner:
            return Response({"code":200,"msg":"ok",'data':banner})
        bannerlist = models.Banner.objects.filter(flag=True).order_by('order')
        ser = homeser.BannerSerializer(bannerlist,many=True)
        cache.set(key,ser.data,60*60*24*7)
        return Response({"code":200,"msg":"ok",'data':ser.data})


from rest_framework.generics import ListAPIView

# 展示轮播图
class BannerList(ListAPIView):
    queryset = models.Banner.objects.filter(flag=True).order_by('order')
    serializer_class = homeser.BannerSerializer

# 文件上传接口
from django.core.files.storage import default_storage
class UploadFile(APIView):
    def post(self,request):
        # 获取到上传的文件 参数设置为file
        file = request.data.get('file')
        # 如果没有大小和类型的限制就可以直接保存了
        # 设置允许的类型
        types = ['jpj','png','jpeg']
        if file.name.split('.')[-1] not in types:
            return Response({"code":"201","msg":"文件类型错误"})
        # 设置允许的大小 b ->kb->mb
        if file.size > 1024*1024*2:
            return Response({"code":"201","msg":"文件过大"})
        # default_storage.save(上传后路径以及文件名字，获取的文件对象)
        uploadfile = default_storage.save("banner/"+file.name,file)
        # 根据上传后的文件获取到路径
        url = default_storage.url(uploadfile)
        return Response({"url":url})